import { fileURLToPath, URL } from "node:url";

import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";

import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import Icons from "unplugin-icons/vite";
import IconsResolver from "unplugin-icons/resolver";
import prerender from "vite-plugin-prerender";

import type { ConfigEnv, UserConfig } from "vite";
import legacy from "@vitejs/plugin-legacy";
const path = require("path");

// https://vitejs.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd());
  return {
    assetsInclude: ["**/*.MP4"],
    server: {
      host: "0.0.0.0",
      port: Number(env.VITE_PORT),
      open: env.VITE_OPEN,
      watch: {
        usePolling: true, // 修复HMR热更新失效
      },
      hmr: true,
      proxy: {
        "/site": {
          target: "http://localhost", //env.VITE_API_URL, //"http://localhost" + env.VITE_PORT,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/site/, ""),
        },
      },
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            prefix: "Icon",
          }),
        ],
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            enabledCollections: ["ep"],
          }),
        ],
      }),
      Icons({
        autoInstall: true,
      }),
      prerender({
        routes: ["/"],
        staticDir: path.join(__dirname, "dist"),
        minify: true,
        fallback: "index.html",
      }),
      legacy({
        targets: ["defaults", "not IE 11"],
        additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
        modernPolyfills: true,
      }),
    ],
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        // find: /^~/, replacement: ''
        // vite解决vue-i18n插件报错
        // vue-i18n.esm-bundler.js:39 You are running the esm-bundler build of vue-i18n.
        // It is recommended to configure your bundler to explicitly replace feature flag
        // globals with boolean literals to get proper tree-shaking in the final bundle.
        "vue-i18n": "vue-i18n/dist/vue-i18n.cjs.js",
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          // additionalData: `@use "~/styles/element/index.scss" as *;`
          additionalData: '@import "@/assets/styles/common/index.scss";',
        },
      },
    },
    build: {
      minify: "terser",
      modulePreload: {
        polyfill: true,
      },
      brotli: true,
      polyfillModulePreload: true,
      terserOptions: {
        compress: {
          //生产环境时移除console.log()
          drop_console: true,
          drop_debugger: true,
        },
      },
      sourcemap: false,
      rollupOptions: {
        output: {
          manualChunks(id: any): string {
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
        },
      },
      target: ["chrome52"],
      cssTarget: ["chrome52"],
    },
    transpileDependencies: true,
  };
});
